package org.jet.emall.security.comp;

import lombok.Setter;
import org.jet.emall.common.constant.RoleName;
import org.jet.emall.rbac.service.CustomAdminUrlPrivilegeRoleViewService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Set;

/**
 * 动态权限管理器实现类，AdminUrlPrivilegeRoleViewService属性必须赋值
 *
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-09 13:15
 */

public class DynamicPrivilegeManagerImpl implements DynamicPrivilegeManager {


    Logger logger = LoggerFactory.getLogger(DynamicPrivilegeManager.class);


    private Map<String, Map<String, Set<String>>> privilegesMap;

    @Setter
    private CustomAdminUrlPrivilegeRoleViewService customAdminUrlPrivilegeRoleViewService;

    @Override
    synchronized public void refresh() {
        if (customAdminUrlPrivilegeRoleViewService == null) {
            throw new RuntimeException("必须设置adminUrlPrivilegeRoleViewService属性的值");
        }

        if (logger.isInfoEnabled()) {
            logger.info("正在加载动态权限信息");
        }
        privilegesMap = customAdminUrlPrivilegeRoleViewService.loadPrivilegesMap();
        if (logger.isInfoEnabled()) {
            logger.info("动态权限信息:\n" + privilegesMap.toString());
        }

    }

    @Override
    public boolean isGrantedFor(String roleName, String url, String method) {
        //如果动态数据不存在，就加载
        if (privilegesMap == null) {
            refresh();
        }
        if (roleName == null || roleName.isEmpty()) {
            return false;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("请求执行一次受权，角色名称:" + roleName + ",url:" + url + ",请求方法:" + method);
        }

        String[] roleNameList = new String[]{roleName, RoleName.BASE_ROLE_NAME};
        for (String role : roleNameList) {
            Map<String, Set<String>> stringSetMap = privilegesMap.get(role);
            if (stringSetMap != null) {
                Set<String> urls = stringSetMap.get(method.toLowerCase());
                if (urls != null) {
                    for (String pattern : urls) {
                        if (url.matches(pattern)) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("针对请求[角色名称:" + roleName + ",url:" + url + ",请求方法:" + method + "]的授权通过");
                            }
                            return true;
                        }
                    }
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("针对请求[角色名称:" + roleName + ",url:" + url + ",请求方法:" + method + "]的授权不通过");
        }
        return false;
    }
}
